package com.kevin.elasticjob.event;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.kevin.elasticjob.util.SpringContextUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Kevin Liu
 * @date 2020/7/31 下午3:41
 */
@Component
@SuppressWarnings("UnstableApiUsage")
public class EventCenter {

    private ThreadPoolExecutor executor = new ThreadPoolExecutor(2,4,2000, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(20));

    /**
     * 管理同步事件
     */
    private final EventBus syncEventBus = new EventBus();

    /**
     * 管理异步事件
     */
    private final AsyncEventBus asyncEventBus = new AsyncEventBus(executor);

    public void postSync(Object event) {
        syncEventBus.post(event);
    }

    public void postAsync(Object event) {
        asyncEventBus.post(event);
    }

    @PostConstruct
    public void init() {

        // 获取所有带有 @EventBusListener 的 bean，将他们注册为监听者
        List<Object> listeners = SpringContextUtils.getBeansWithAnnotation(EventBusListener.class);
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
    }

}
